//
//  SearchViewController.m
//  miaopai
//
//  Created by duyifang on 15/11/19.
//  Copyright © 2015年 Crow Zhang. All rights reserved.
//

#import "SearchViewController.h"
#import "CustomerNetworking.h"
#import "NewsTopicModel.h"
#import "SearchRow0TableViewCell.h"
#import "SearchOtherTableViewCell.h"
#import "SearchTopicModel.h"
#import "Channel.h"
#import "SearchTopicButtonTableViewCell.h"
#import "CollectionVideoTableViewCell.h"
#import "SearchHeaderTableViewCell.h"
#import "SearchMoreTopicsViewController.h"
#import "TopicDetailViewController.h"
#import "VideoDetailViewController.h"
@interface SearchViewController ()<UITableViewDataSource, UITableViewDelegate, SearchRow0TableViewCellDelegate, UISearchBarDelegate, SearchTopicButtonTableViewCellDelegate>

@property(nonatomic, retain) UISearchBar *searchBar;

@property(nonatomic, retain) UITableView *hotTableView;

@property(nonatomic, retain) UIView *historyView;

@property(nonatomic, retain) NSMutableArray *hotModelArray;

@property(nonatomic, retain) NSMutableArray *arcModelArray;

@property(nonatomic, retain) NSMutableArray *searchTopicModelArray;

@property(nonatomic, retain) NSMutableArray *searchVideoModelArray;

@property(nonatomic, retain) UITableView *searchTableView;

@property(nonatomic, retain) UILabel *noResultLabel;

@property(nonatomic, retain) UITableView *historyTableView;

@property(nonatomic, retain) NSMutableArray *searchHistoryArray;

@property(nonatomic, copy) NSString *cachesArrayPath;

@property(nonatomic, retain) NSArray *historyArray;

@end

@implementation SearchViewController

- (void)dealloc
{
    [_searchBar release];
    [_hotTableView release];
    [_historyView release];
    [_hotModelArray release];
    [_arcModelArray release];
    [_searchTopicModelArray release];
    [_searchVideoModelArray release];
    [_searchTableView release];
    [_noResultLabel release];
    [_historyTableView release];
    [_searchHistoryArray release];
    [_cachesArrayPath release];
    [_historyArray release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"搜索";
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    
    self.hotModelArray = [NSMutableArray array];
    self.arcModelArray = [NSMutableArray array];
    self.searchTopicModelArray = [NSMutableArray array];
    self.searchVideoModelArray = [NSMutableArray array];
    self.searchHistoryArray = [NSMutableArray array];
    
    NSArray *array = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachesArray = [array lastObject];
    self.cachesArrayPath = [cachesArray stringByAppendingPathComponent:@"search.txt"];
    self.historyArray = [NSArray arrayWithContentsOfFile:_cachesArrayPath];

    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 50)];
    _searchBar.placeholder = @"搜索视频、话题";
    _searchBar.delegate = self;
    [_searchBar setContentMode:UIViewContentModeLeft];
    [self.view addSubview:_searchBar];
    [_searchBar release];
    
    [self downloadData];
    [self creatSubView];
}

- (void)downloadData
{
    [CustomerNetworking customerConnectWithURL:@"http://api.miaopai.com/m/topic_rank.json?os=ios&page=1&per=50&unique_id=d148d7c2b9c27f685d9be7639517be5e3661826668&version=6.2.1" andparameters:nil andBlock:^(id response) {
        NSDictionary *bigDic = response;
        NSArray *resultArray = [bigDic objectForKey:@"result"];
        for (NSDictionary *dic in resultArray) {
            NewsTopicModel *newsTopicModel = [NewsTopicModel newsTopicModelWithDictionary:dic];
            [_hotModelArray addObject:newsTopicModel];
        }
        if (_hotModelArray.count != 0) {
            if (_arcModelArray.count != 0) {
                [_arcModelArray removeAllObjects];
            }
            NSInteger temp = arc4random() % (_hotModelArray.count - 4);
            for (NSInteger i = 0; i < 4; i++) {
                [_arcModelArray addObject:[_hotModelArray objectAtIndex:temp + i]];
            }
        }
        [_hotTableView reloadData];
    }];

}

- (void)creatSubView
{
    self.hotTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, _searchBar.frame.origin.y + _searchBar.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - _searchBar.frame.origin.y - _searchBar.frame.size.height) style:UITableViewStylePlain];
    _hotTableView.delegate = self;
    _hotTableView.dataSource = self;
    _hotTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [_hotTableView registerClass:[SearchRow0TableViewCell class] forCellReuseIdentifier:@"SearchRow0TableViewCell"];
    [_hotTableView registerClass:[SearchOtherTableViewCell class] forCellReuseIdentifier:@"SearchOtherTableViewCell"];
    [self.view addSubview:_hotTableView];
    [_hotTableView.tableFooterView release];
    [_hotTableView release];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([tableView isEqual:_hotTableView]) {
        return _arcModelArray.count;
    }else if ([tableView isEqual:_searchTableView])
    {
        if (section == 0) {
            if (_searchTopicModelArray.count == 0) {
                return 0;
            }else
            {
                return 5;
            }
        }else
        {
            if (_searchVideoModelArray.count == 0) {
                return 0;
            }else
            {
                return _searchVideoModelArray.count + 1;
            }
        }
    }else
    {
        return _historyArray.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:_hotTableView]) {
        if (indexPath.row == 0) {
            return 40;
        }else
        {
            return 90;
        }

    }else if ([tableView isEqual:_searchTableView])
    {
        if (indexPath.section == 0) {
            if (indexPath.row == 0) {
                return 25;
            }else
            {
                return 44;
            }
        }else
        {
            if (indexPath.row == 0) {
                return 25;
            }else
            {
                return self.view.frame.size.width;
            }
        }
    }else
    {
        return 44;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:_hotTableView]) {
        if (indexPath.row == 0) {
            SearchRow0TableViewCell *cell = [[SearchRow0TableViewCell alloc] init];
            cell.backgroundColor = [UIColor colorWithRed:0.8824 green:0.8824 blue:0.8824 alpha:1.0];
            cell.delegate = self;
            return cell;
        }else
        {
            SearchOtherTableViewCell *cell = [[SearchOtherTableViewCell alloc] init];
            if (_hotModelArray > 0) {
                cell.hotModel = [_arcModelArray objectAtIndex:indexPath.row - 1];
            }
            return cell;
        }
    }else if ([tableView isEqual:_searchTableView])
    {
        if (indexPath.section == 0) {
            if (indexPath.row == 0) {
                SearchHeaderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchHeaderTableViewCell" forIndexPath:indexPath];
                cell.labelString = @"话题";
                cell.backgroundColor = [UIColor colorWithRed:0.8382 green:0.8382 blue:0.8382 alpha:1.0];
                return cell;
            }else if (indexPath.row > 0 && indexPath.row < 4)
            {
                UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
                if (_searchTopicModelArray.count > 0) {
                    SearchTopicModel *topicModel = (SearchTopicModel *)[_searchTopicModelArray objectAtIndex:indexPath.row - 1];
                    cell.textLabel.text = topicModel.name;
                }
                return cell;
            }else
            {
                SearchTopicButtonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchTopicButtonTableViewCell" forIndexPath:indexPath];
                cell.delegate = self;
                return cell;
            }
        }else
        {
            if (indexPath.row == 0) {
                SearchHeaderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchHeaderTableViewCell" forIndexPath:indexPath];
                cell.labelString = @"视频";
                cell.backgroundColor = [UIColor colorWithRed:0.8382 green:0.8382 blue:0.8382 alpha:1.0];
                return cell;
            }else
            {
                CollectionVideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CollectionVideoTableViewCell" forIndexPath:indexPath];
                Channel *channel = [_searchVideoModelArray objectAtIndex:indexPath.row - 1];
                cell.channel = channel;
                cell.backgroundColor = [UIColor whiteColor];
                if (indexPath.row == 0) {
                    cell.stream = [NSString stringWithFormat:@"%@%@.%@", channel.stream.base, channel.scid, channel.stream.and];
                }
                return cell;
            }
        }
    }else
    {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HistoryTableViewCell" forIndexPath:indexPath];
        cell.textLabel.text = [_historyArray objectAtIndex:indexPath.row];
        return cell;
    }
}

- (void)changeTableViewData
{
    [self downloadData];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = YES;
    NSLog(@"%@", searchBar.subviews);
    for (UIButton *cancelButton in [searchBar.subviews[0] subviews]) {
        if ([cancelButton isKindOfClass:[UIButton class]]) {
            [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
            [cancelButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
    }
    
    self.historyView = [[UIView alloc] initWithFrame:CGRectMake(0, _searchBar.frame.size.height + _searchBar.frame.origin.y, self.view.frame.size.width, 0)];
    UILabel *historyLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 80, 30)];
    historyLabel.text = @"历史搜索 :";
    historyLabel.font = [UIFont systemFontOfSize:15];
    historyLabel.textColor = [UIColor colorWithRed:0.5639 green:0.5639 blue:0.5639 alpha:1.0];
    UILabel *noSearchLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, (_historyView.frame.size.height - historyLabel.frame.size.height - 20) / 2, _historyView.frame.size.width, 0)];
    noSearchLabel.text = @"还没有历史搜索记录...";
    noSearchLabel.textColor = [UIColor colorWithRed:0.5639 green:0.5639 blue:0.5639 alpha:1.0];
    noSearchLabel.font = [UIFont systemFontOfSize:15];
    noSearchLabel.textAlignment = NSTextAlignmentCenter;
    [_historyView addSubview:noSearchLabel];
    [_historyView addSubview:historyLabel];
    _historyView.backgroundColor = [UIColor whiteColor];
    
    self.historyArray = [NSArray arrayWithContentsOfFile:_cachesArrayPath];
    NSLog(@"%@", _cachesArrayPath);
    if (_historyArray.count != 0) {
        self.historyTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 30, _historyView.frame.size.width, 0) style:UITableViewStylePlain];
        _historyTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        _historyTableView.delegate = self;
        _historyTableView.dataSource = self;
        [_historyTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"HistoryTableViewCell"];
        [_historyView addSubview:_historyTableView];
        [_historyTableView.tableFooterView release];
        [_historyTableView release];
    }
    
    [UIView animateWithDuration:0.5 animations:^{
        _historyView.frame = CGRectMake(0, _historyView.frame.origin.y, _historyView.frame.size.width, _hotTableView.frame.size.height);
        noSearchLabel.frame = CGRectMake(0, (_historyView.frame.size.height - historyLabel.frame.size.height - 20) / 2, _historyView.frame.size.width, 20);
        _historyTableView.frame = CGRectMake(0, 30, _historyView.frame.size.width, _historyView.frame.size.height - 30);
    }];
    
    [self.view addSubview:_historyView];
    [_historyView release];
    [historyLabel release];
    return YES;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    searchBar.showsCancelButton = NO;
    [_historyView removeFromSuperview];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [_searchHistoryArray addObject:searchBar.text];

    [_searchHistoryArray writeToFile:_cachesArrayPath atomically:YES];
    
    searchBar.showsCancelButton = NO;
    [_searchTableView removeFromSuperview];
    [_searchBar resignFirstResponder];
    NSString *searchText = [searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [self getTopicData:searchText];
    [self getVideoData:searchText];
    [self creatSearchTableView];
}

- (void)getTopicData:(NSString *)searchText
{
    [CustomerNetworking customerConnectWithURL:[NSString stringWithFormat:@"http://api.miaopai.com/m/search_topic.json?keyword=%@&more=1&os=ios&page=1&per=20&unique_id=d148d7c2b9c27f685d9be7639517be5e3661826668&version=6.2.1", searchText] andparameters:nil andBlock:^(id response) {
        if (_searchTopicModelArray.count != 0) {
            [_searchTopicModelArray removeAllObjects];
        }
        NSDictionary *bigDic = response;
        NSArray *bigArray = [bigDic objectForKey:@"result"];
        for (NSDictionary *dic in bigArray) {
            SearchTopicModel *topicModel = [SearchTopicModel searchTopicModelWithDictionary:dic];
            [_searchTopicModelArray addObject:topicModel];
        }
        if (_searchTopicModelArray.count == 0) {
            _noResultLabel.alpha = 1;
        }else
        {
            _noResultLabel.alpha = 0;
        }
        [_searchTableView reloadData];
    }];
}

- (void)getVideoData:(NSString *)searchText
{
    
    [CustomerNetworking customerConnectWithURL:[NSString stringWithFormat:@"http://api.miaopai.com/m/search-channel.json?keyword=%@&more=1&os=ios&page=1&per=20&unique_id=d148d7c2b9c27f685d9be7639517be5e3661826668&version=6.2.1", searchText] andparameters:nil andBlock:^(id response) {
        if (_searchVideoModelArray != 0) {
            [_searchVideoModelArray removeAllObjects];
        }
        NSDictionary *bigDic = response;
        NSArray *bigArray = [bigDic objectForKey:@"result"];
        for (NSDictionary *dic in bigArray) {
            Channel *videoModel = [Channel channelWithDic:[dic objectForKey:@"channel"]];
            [_searchVideoModelArray addObject:videoModel];
        }
        [_searchTableView reloadData];
    }];

}

- (void)creatSearchTableView
{
    self.searchTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, _searchBar.frame.size.height + _searchBar.frame.origin.y, self.view.frame.size.width, _hotTableView.frame.size.height) style:UITableViewStylePlain];
    _searchTableView.delegate = self;
    _searchTableView.dataSource = self;
    [_searchTableView registerClass:[SearchHeaderTableViewCell class] forCellReuseIdentifier:@"SearchHeaderTableViewCell"];
    [_searchTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    [_searchTableView registerClass:[SearchTopicButtonTableViewCell class] forCellReuseIdentifier:@"SearchTopicButtonTableViewCell"];
    [_searchTableView registerClass:[CollectionVideoTableViewCell class] forCellReuseIdentifier:@"CollectionVideoTableViewCell"];
    _searchTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    _searchTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:_searchTableView];
    [_searchTableView.tableHeaderView release];
    [_searchTableView.tableFooterView release];
    [_searchTableView release];
    
    self.noResultLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, (_searchTableView.frame.size.height - 30) / 2, self.view.frame.size.width, 30)];
    _noResultLabel.text = @"没有找到相应的内容...";
    _noResultLabel.textColor = [UIColor colorWithRed:0.6265 green:0.6265 blue:0.6265 alpha:1.0];
    _noResultLabel.textAlignment = NSTextAlignmentCenter;
    _noResultLabel.alpha = 0;
    [_searchTableView addSubview:_noResultLabel];
    [_noResultLabel release];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if ([tableView isEqual:_hotTableView]) {
        return 1;
    }else if ([tableView isEqual:_searchTableView])
    {
        return 2;
    }else
    {
        return 1;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:_hotTableView]) {
        if (indexPath.row > 0) {
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
            TopicDetailViewController *topicDetailViewController = [[TopicDetailViewController alloc] init];
            NewsTopicModel *topicModel = [_arcModelArray objectAtIndex:indexPath.row - 1];
            topicDetailViewController.stpid = topicModel.topic.stpid;
            topicDetailViewController.topicName = topicModel.topic.name;
            UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
            backItem.title = @"";
            self.navigationItem.backBarButtonItem = backItem;
            [backItem release];
            [self.navigationController pushViewController:topicDetailViewController animated:YES];
            [topicDetailViewController release];
        }
    }else if ([tableView isEqual:_searchTableView])
    {
        if (indexPath.section == 0) {
            if (indexPath.row > 0 && indexPath.row < 4) {
                [tableView deselectRowAtIndexPath:indexPath animated:YES];
                TopicDetailViewController *topicDetailViewController = [[TopicDetailViewController alloc] init];
                SearchTopicModel *searchTopicModel = [_searchTopicModelArray objectAtIndex:indexPath.row - 1];
                UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
                backItem.title = @"";
                self.navigationItem.backBarButtonItem = backItem;
                [backItem release];
                topicDetailViewController.stpid = searchTopicModel.stpid;
                topicDetailViewController.topicName = searchTopicModel.name;
                [self.navigationController pushViewController:topicDetailViewController animated:YES];
                [topicDetailViewController release];

            }
        }else
        {
            if (indexPath.row > 0) {
                [tableView deselectRowAtIndexPath:indexPath animated:YES];

                VideoDetailViewController *videoDetailViewController = [[VideoDetailViewController alloc] init];
                videoDetailViewController.scid = [[_searchVideoModelArray objectAtIndex:indexPath.row - 1] scid];
                UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
                backItem.title = @"返回";
                self.navigationItem.backBarButtonItem = backItem;
                [backItem release];
                [self.navigationController pushViewController:videoDetailViewController animated:YES];
                [videoDetailViewController release];
            }
        }
    }else
    {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        _searchBar.text = [_historyArray objectAtIndex:indexPath.row];
    }
}

- (void)pushToMoreTopicsViewController
{
    SearchMoreTopicsViewController *topicsViewController = [[SearchMoreTopicsViewController alloc] init];
    topicsViewController.topicsArray = _searchTopicModelArray;
    [self.navigationController pushViewController:topicsViewController animated:YES];
    [topicsViewController release];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    UIView * view = [self.tabBarController.view.subviews lastObject];
    [UIView animateWithDuration:0.5 animations:^{
        view.frame = CGRectMake(0, kHeight + 100, kWidth, 48);
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
